from sshtunnel import SSHTunnelForwarder

import paramiko
import subprocess
import sshtunnel
import requests

def ssh_remote_addr():
    with paramiko.SSHClient() as client:
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # client.load_system_host_keys()
        client.connect('118.145.151.90',22, username='root', password='0S^tNOHRgNMw')
        if client.get_transport().is_active():
            stdin, stdout,stderr = client.exec_command('ip addr')
            print(stdout.read().decode())
        else:
            print('invalid')
        client.close()

def ssh_remote_tunnel():
    server = SSHTunnelForwarder(
        ssh_address_or_host=('118.145.151.90',22),
        ssh_username="root",
        ssh_password="0S^tNOHRgNMw",
        remote_bind_address=('127.0.0.1', 8000)
    )

    server.start()

    print(server.local_bind_addresses)  # show assigned local port
    # work with `SECRET SERVICE` through `server.local_bind_port`.
    # completed_process = subprocess.run("ping 192.168.60.7")
    # print(completed_process.stdout)
    resp = requests.get(f'http://localhost:{server.local_bind_port}/static/css/app.d8f16ddd.css')
    print(resp.text)
    server.stop()

def simple_remote_tunnel():
    with sshtunnel.open_tunnel(
        ssh_address_or_host=('118.145.151.8',22),
        ssh_username="root",
        ssh_password="0S^tNOHRgNMw",
        remote_bind_address=('127.0.0.1', 8088)
    ) as server:
        # 访问远程服务器商指定端口的服务
        resp = requests.get(f'http://localhost:{server.local_bind_port}/cluster')
        print(resp.text)

def remote_private_with_ssh_operate():
    REMOTE_SERVER_IP = '118.145.151.90'
    # REMOTE_SERVER_IP ='118.145.151.8'
    REMOTE_SERVER_PORT = 22
    PRIVATE_SERVER_IP = '192.168.60.7'

    with sshtunnel.open_tunnel(
        (REMOTE_SERVER_IP, REMOTE_SERVER_PORT),
        ssh_username="root",
        ssh_password="0S^tNOHRgNMw",
        remote_bind_address=(PRIVATE_SERVER_IP, 22),
        local_bind_address=('0.0.0.0', 10022)
    ) as tunnel:
        # print(tunnel.local_is_up)
        with paramiko.SSHClient() as client:
            client.load_system_host_keys()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect('localhost',tunnel.local_bind_port, username='root', password='0S^tNOHRgNMw')
            if client.get_transport().is_active():
                stdin, stdout,stderr = client.exec_command('ip addr')
                print(stdout.read().decode())
            else:
                print('invalid')
            client.close()
        


    print('FINISH!')

    
if __name__=='__main__':
    # ssh_remote_server()
    # ssh_remote_addr()
    # simple_remote_tunnel()
    # remote_private_with_ssh_operate()
    ssh_remote_tunnel()
